package com.xuanyuanxinyu.func.network.retrofit

import android.annotation.SuppressLint
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSession
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager

/**
 * CM
 *
 * @author ken.luo
 */
object SSLSocketClient {
    //获取TrustManager
    val trustManager : Array<X509TrustManager> = arrayOf(getx509TrustManager())
    
    //获取HostnameVerifier
    val hostnameVerifier : HostnameVerifier = HostnameVerifier { s : String?,sslSession : SSLSession?-> true }
    
    /**
     * 获取这个SSLSocketFactory
     */
    fun sSLSocketFactory() : SSLSocketFactory {
        try {
            //            SSLContext sslContext = SSLContext.getInstance("SSL");
            //            sslContext.init(null, getTrustManager(), new SecureRandom());
            // 证书格式不一样
            //            SSLContext sslContext = SSLContext.getInstance("SSL");
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, trustManager,SecureRandom())
            //实用信任的证书库
            //            sslContext.init(null, null, null);
            return sslContext.socketFactory
        } catch (e : Exception) {
            throw RuntimeException(e)
        }
    }
    
    @SuppressLint("CustomX509TrustManager","TrustAllX509TrustManager")
    private fun getx509TrustManager() : X509TrustManager {
        return object : X509TrustManager {
            override fun checkClientTrusted(chain : Array<X509Certificate>,authType : String) {
            }
            
            override fun checkServerTrusted(chain : Array<X509Certificate>,authType : String) {
            }
            
            override fun getAcceptedIssuers() : Array<X509Certificate> {
                return arrayOf()
            }
        }
    }
}
